package test.test2;

import java.io.*;
import java.net.*;
import java.util.Scanner;

public class Client {
    private Socket socket = null;

    public Client(String severIp, int serverPort) throws IOException {
        // socket 构造方法, 能够识别点分十进制格式的 IP 地址, 比 DatagramPacket 更方便
        // new 这个对象的同时, 就会进行 TCP 的连接操作
        socket = new Socket(severIp, serverPort);
    }

    public void start() {
        System.out.println("客户端启动");
        Scanner in = new Scanner(System.in);
        try (InputStream inputStream = socket.getInputStream();
             OutputStream outputStream = socket.getOutputStream()) {
            while (true) {
                // 1. 从键盘上读取用户的内容
                System.out.print("> ");
                String request = in.next();
                if (request.equals("exit")) {
                    break;
                }
                // 2. 把读取到的内容构造成请求, 发送给服务器
                PrintWriter printWriter = new PrintWriter(outputStream);
                printWriter.println(request);
                printWriter.flush();
                // 3. 读取服务器的响应
                Scanner respScanner = new Scanner(inputStream);
                String response = respScanner.next();
                // 4. 把响应的内容显示到界面上
                System.out.println(response);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        Client client = new Client("127.0.0.1", 8888);
        client.start();
    }
}
